// 防抖 -> 延迟执行
function debounce(fn, delay = 300) {   //默认300毫秒
    var timer;
    return function() {
        var args = arguments;
        if(timer) {
            clearTimeout(timer);
        }
        timer = setTimeout(() => {
            fn.apply(this, args);   // this 指向vue
        }, delay);
    };
}

// 节流 -> 固定频率执行
function throttle (fn,interval,timeout) {
    let previous = null;
    let timer = null;

    return function () {

        let now = new Date();

        if (!previous) previous = now;

        if (now - previous > interval) {
            clearTimeout(timer);
            fn();
            previous = now;
        } else {
            clearTimeout(timer);
            timer = setTimeout(() => {
                fn();
            }, timeout);
        }

    }

}

export {
    debounce,
    throttle
}